Back to Article
neighborhood_agg.ipynb
Download Notebook
In [1]:
from zfish.features.neighborhood.neighborhoods import NeighborhoodQueryObject
from zfish.features.neighborhood.aggregation_functions import Mean, Median
from zfish.multi_table.tables_io import scan_features, scan_resources
from zfish.roi.spatial_roi import Roi
from zfish.visualize.napari_utils import napari_centroids
from zfish.roi.visualize import imshow_si
from pathlib import Path
import polars as pl
In [2]:
r = scan_resources().collect()
fl = scan_features()
In [3]:
roi_name = 'F03_px-2043_py+0598'

fl_roi = fl.filter(pl.col("roi") == roi_name)
r_roi = r.filter(pl.col('roi')==roi_name)

f_nuc = fl_roi.filter(pl.col("o") == "nucleiRaw3").collect()
r_nuc = r_roi.filter(pl.col("o") == "nucleiRaw3")


df_nuc = f_nuc.label
df_feat = df_nuc.select(pl.col('PhysicalSize'))
In [4]:
nqo = NeighborhoodQueryObject.from_dataframe(
    df_nuc,
)
In [5]:
knn_k = [0, 1, 2, 3, 5, 6, 8, 10, 13, 16, 20, 25, 30, 35, 40, 50, 60, 70, 80, 100]

res = nqo.knn(knn_k, self_loops=True).aggregate(
    Median, df_feat
)
The TBB threading layer requires TBB version 2021 update 6 or later i.e., TBB_INTERFACE_VERSION >= 12060. Found TBB_INTERFACE_VERSION = 12030. The TBB threading layer is disabled.
In [6]:
nqo.knn(knn_k, self_loops=True).neighborhoods
<generator object NeighborhoodQueryObject.neighborhoods at 0x0000021C29F775A0>
In [7]:
from libpysal.weights import W
from zfish.visualize.pyvista_utils import write_gif, plot_points, get_points, generate_arc_path, orbit_on_path
import pyvista as pv
from pathlib import Path

weights = W.from_sparse(next(nqo.radius([50, 100], self_loops=False).neighborhoods))
In [19]:


df = r_nuc.label_objects.with_columns(res)
features = res.columns
hue_norm = (400, 3000)
palette = "turbo"
out_fld = Path(
    r"C:\Users\hessm\Documents\Programming\Python\thesis\Figures\Results\FeatureExtraction"
)


default_cpos = [
    (-523.8876415858913, 846.4374533511898, -89.23640708215856),
    (172.0002900053642, 402.54420556060376, 284.4726164866637),
    (-0.6399956399907923, -0.5638948033048345, 0.5219465792574735),
]
points = get_points(df, features=features)


po = pv.Plotter(
    notebook=False,
    off_screen=True,
    point_smoothing=True,
    line_smoothing=True,
    polygon_smoothing=True,
    image_scale=2,
)
po = plot_points(
    points,
    po=po,
    hue=features[0],
    hue_norm=hue_norm,
    palette=palette,
    size=35,
    silhouette=True,
    show_scalar_bar=False,
    show_edges=True,
)
po.camera_position = default_cpos
# cpos = po.show(return_cpos=True)
In [20]:
for i, f in enumerate(features[::10]):
    out_fn = out_fld / f"physical_size_median_knn0-20_{i}.png"
    # po.image_scale = 2
    po.mesh.set_active_scalars(f)

    po.add_text(
        f"KNN {f.split('_')[0].split(':')[1].removesuffix('s')}",
        position="upper_left",
        font_size=42,
        color=None,
        font=None,
        shadow=False,
        name="text",
        viewport=False,
        orientation=0.0,
        font_file=None,
        render=True,
    )
    # po.save_graphic(out_fn)
    po.screenshot(out_fn)
In [21]:
out_gif = out_fld / "physical_size_median_knn0-100.gif"

po.open_gif(out_gif, fps=5)
for f in features:
    # po.image_scale = 2
    po.mesh.set_active_scalars(f)
    po.add_text(
        f"KNN {f.split('_')[0].split(':')[1].removesuffix('s'):>3}",
        position="upper_left",
        font_size=42,
        color=None,
        font=None,
        shadow=False,
        name="text",
        viewport=False,
        orientation=0.0,
        font_file=None,
        render=True,
    )
    po.write_frame()
po.close()
In [1]:
# out_gif = out_fld / "__physical_size_median_knn0-100.gif"

# callbacks = [
#     {
#         "mesh.set_active_scalars": {"name": f},
#         "add_text": {
#             "text": f"KNN {f.split('_')[0].split(':')[1].removesuffix('s'):>3}",
#             "font_size": 42,
#             'name': 'text',
#         },
#     }
#     for f in features
# ]
# po.open_gif(out_gif, fps=5)

# path = generate_arc_path(n_points=len(features), plotter=po, viewup=(-1, 0, 0))
# orbit_on_path(plotter=po, path=path, write_frames=True, viewup=(-1, 0, 0))

# # for i, f in enumerate(features):
# #     # po.image_scale =
# #     for k, callback in callbacks[i].items():
# #         attrs = k.split(".")
# #         func = po
# #         for attr in attrs:
# #             func = getattr(func, attr)
# #         func(**callback)

# #     po.write_frame()
# # po.close()